/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.cluster.impl;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;

import org.jgroups.util.Streamable;
import org.sabayframework.cluster.ClusterId;
import org.sabayframework.cluster.Computer;
import org.sabayframework.cluster.ComputerId;
import org.sabayframework.cluster.NodeExecutionQueue;
import org.sabayframework.cluster.NodeId;
import org.sabayframework.cluster.NodeMapping;


public class RemoteComputer extends BaseNode<ComputerId, ClusterId> implements Computer, Serializable, Streamable {
	private static final long serialVersionUID = 1L;
	private NodeId[] processors;
	private NodeMapping nodeMapping;
	private NodeExecutionQueue executionQueue;
	
	RemoteComputer() {
		super(new ComputerIdImpl(null, 0));
	}

	public RemoteComputer(LocalComputer local) {
		super(local.getComputerId());
		this.executionQueue = local.getExecutionQueue();
		processors = local.getChildrenIds();
		nodeMapping = local.getChildrenMapping();
	}
	
	@Override
	public ComputerId getComputerId() {
		return id;
	}

	@Override
	public int getChildrenCount() {
		return processors.length;
	}
	
	@Override
	public NodeId[] getChildrenIds() {
		return processors;
	}
	@Override
	public NodeMapping getChildrenMapping() {
		return nodeMapping;
	}

	@Override
	public void readFrom(DataInput in) throws IOException {
		ComputerIdImpl id = (ComputerIdImpl)getId();
		id.readFrom(in);
		final int len = in.readUnsignedShort();
		ProcessorIdImpl[] processors = new ProcessorIdImpl[len];
		for(int i=0;i<len;++i){
			processors[i] = new ProcessorIdImpl(id, i+1);
		}
		nodeMapping = new ModuloNodeMapping<ProcessorIdImpl>(processors);
		this.processors = processors;
		this.executionQueue = new RemoteExecutionQueue(this);
	}

	@Override
	public void writeTo(DataOutput out) throws IOException {
		ComputerIdImpl id = (ComputerIdImpl)getId();
		id.writeTo(out);
		out.writeShort(processors.length);
	}

	@Override
	public String toString() {
		return "RemoteComputer [" + getId()+ ", processors=" + processors.length + "]";
	}

	@Override
	public NodeExecutionQueue getExecutionQueue() {
		return executionQueue;
	}
	
}
